package naga.x.net.impl.pomelo.config;

import java.util.Base64;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;

import naga.x.net.impl.pomelo.protocol.Protocol;
import naga.x.util.CommonUtils;
import naga.x.util.StringUtils;

public class Dictionary {
	
	private Map<String, Short> dict; // route->code
	private Map<String, String> abbrs; // code->route
	private String version;
	private Map<Short, Class<?>> classesOfRequest;
	
	public Dictionary() {
	}
	
	public Dictionary(Map<String, Short> dict) {
		this(dict, null);
	}
	
	public Dictionary(Map<String, Short> dict, Map<Short, Class<?>> classesOfRequest) {
		if (!(dict instanceof LinkedHashMap)) {
			dict = new LinkedHashMap<String, Short>(dict);
		}
		Iterator<Entry<String, Short>> itr = dict.entrySet().iterator();
		Map<String, String> abbrs = new LinkedHashMap<String, String>(dict.size());
		while (itr.hasNext()) {
			Entry<String, Short> e = itr.next();
			abbrs.put(String.valueOf(e.getValue()), e.getKey());
		}
		this.dict = dict;
		this.abbrs = abbrs;
		version = Protocol.strdecode(Base64.getEncoder().encode(CommonUtils.encrypt("MD5", JSON.toJSONBytes(dict))));
		this.classesOfRequest = classesOfRequest;
	}

	public Map<String, Short> getDict() {
		return dict;
	}

	public void setDict(Map<String, Short> dict) {
		this.dict = dict;
	}

	public Map<String, String> getAbbrs() {
		return abbrs;
	}

	public void setAbbrs(Map<String, String> abbrs) {
		this.abbrs = abbrs;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public Map<Short, Class<?>> getClassesOfRequest() {
		return classesOfRequest;
	}

	public void setClassesOfRequest(Map<Short, Class<?>> classesOfRequest) {
		this.classesOfRequest = classesOfRequest;
	}
	
	public Class<?> getRequestClass(Short routeCode) {
		return routeCode != null && classesOfRequest != null ? classesOfRequest.get(routeCode) : null;
	}
	
	public Class<?> getRequestClass(String routeName) {
		return dict != null ? getRequestClass(dict.get(routeName)) : null;
	}
	
	public short getRouteCode(String route) {
		Short code;
		return (short) (StringUtils.isNotEmpty(route) && dict != null ? ((code = dict.get(route)) != null ? code.shortValue() : -1) : -1);
	}
	
	public String getRoute(short routeCode) {
		return abbrs != null ? abbrs.get(String.valueOf(routeCode)) : null;
	}
	
}
